package org.intrasearch.core;

import com.google.inject.Inject;
import com.google.inject.Singleton;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

@Singleton
public class ArtifactSearcherImpl implements ArtifactSearcher
{
    private final InvertedIndex invertedIndex;
    private final ArtifactStorage artifactStorage;

    @Inject
    public ArtifactSearcherImpl(InvertedIndex invertedIndex, ArtifactStorage artifactStorage)
    {
        this.invertedIndex = invertedIndex;
        this.artifactStorage = artifactStorage;
    }

    public List<Artifact> searchQuery(String query)
    {
        List<ArtifactId> artifactIds = new ArrayList<ArtifactId>();
        for (StringTokenizer stringTokenizer = new StringTokenizer(query, InvertedIndex.WORD_DELIMETER); stringTokenizer.hasMoreTokens();)
        {
            String word = stringTokenizer.nextToken().toLowerCase();
            if (artifactIds.isEmpty())
            {
                artifactIds.addAll(invertedIndex.artifactsByWord(word));
            }
            else
            {
                artifactIds.retainAll(invertedIndex.artifactsByWord(word));
            }
        }

        return artifactStorage.artifactsByIds(artifactIds);
    }
}
